import { AfterViewInit, Component, OnInit, ViewChild } from "@angular/core";
import { Util } from "../../../common/util";
import { ActivatedRoute } from "@angular/router";
import { TransferInstructionManageService } from "./transfer-instructionManage.service";

import { ListComponent } from './list/list.component';
import { PaginationModel } from "../../../widgets/pagination/pagination.component";
import { Subscription } from "rxjs/Subscription";
import { Store } from "@ngrx/store";
import { InterbankToTransferExchangeDataModel } from "../../../actionReducer/interbank-to-transfer/interbank-to-transfer.reducer";
import { Observable } from "rxjs/Observable";

/**
 * 划款指令列表搜索数据模型
 */
export interface TFISeacrhModel {
  /**
   * 款项类型
   */
  hkTypeId?: string;
  /**
   * 指令开始日期
   */
  startDate?: string;
  /**
   * 指令结束日期
   */
  endDate?: string;
  /**
   * 指令状态
   */
  hkInstructionStatus?: string;
  /**
   * 指令编号
   */
  hkInstructionId?: string;
  /**
   * 基金代码
   */
  fundCode?: string;
  /**
   * 基金名称
   */
  fundName?: string;
  /**
   * 股票代码
   */
  stockCode?: string;
  /**
   * 股票名称
   */
  stockName?: string;
  [propName: string]: any;
}

@Component({
  selector: 'transfer-instruction',
  templateUrl: './transfer-instructionManage.component.html',
  styleUrls: ['./transfer-instructionManage.component.scss']
})

export class TransferInstructionManageComponent implements OnInit, AfterViewInit {

  public $ = window['$'];

  /**
   * 当前Tab切换划款指令类型状态变量,
   * 默认为空，全部
   *  1 待确认
   *  2 待复核
   *  4 待审核
   *  6 待发送
   *  8 已发送
   *  9 已到账
   *  10 已撤销
   * @memberof TransferInstructionManageComponent
   */
  public nowStatus: any = "";

  /**
   * 操作按钮下允许操作的划款指令状态
   * 例如：确认划款指令按钮只允许划款指令状态为1的数据进行操作
   */
  public allStatus: any = {
    // 确认划款指令
    qrhkzl: ['1'],
    // 复核划款指令
    fhhkzl: ['2'],
    // 审核划款指令
    shhkzl: ['4'],
    // 发送划款指令
    fshkzl: ['6'],
    // 指令驳回
    zlbh: ["all"],
    // 指令撤销
    zlcx: ['1', '2', '3', '4'],
    // 手工到账确认
    sgdzqr: ['8']
  };

  /**
   * 划款指令状态集合
   * @memberof ListComponent
   */
  public status: any = {
    "1": "待确认",
    "2": "待复核",
    "3": "初审驳回",
    "4": "待审核",
    "5": "复核驳回",
    "6": "待发送",
    "7": "发送托管行出款",
    "8": "手工到账确认",
    "9": "已到账",
    "10": "已撤销"
  };

  /**
   * 划款指令类型集合
   * 用于ListComponent 转义
   * @memberof ListComponent
   */
  public hkType: any = {
    "XGSG_SQ_IPO_SH": "新股申购-上海",
    "XGSG_SQ_IPO_SZ": "新股申购-深圳",
    "ZJHH_DVP_SQS_TC": "调出DVP账户（上清所）",
    "ZJHH_DVP_SQS_TR": "调入DVP账户（上清所）",
    "ZJHH_DVP_ZZ_TC": "调出DVP账户（中债） ",
    "ZJHH_DVP_ZZ_TR": "调入DVP账户（中债）"
  };

  /**
   * 业务类型集合
   * 用于ListComponent 转义
   * @memberof ListComponent
   */
  public bizType: any = {
    "1": "银行间业务",
    "2": "新股网下申购",
    "3": "定存",
    "4": "债券分销",
    "5": "期货出入金 ",
    "6": "QDII换汇",
    "7": "席位佣金支付",
    "8": "审计费"
  };

  // 划款指令查询请求返回的列表数据
  public data: any = {
    list: []
  };

  /**
   * 点击列后，从List.component返回的行数据
   * @type {{any}}
   */
  public acceptData: any = {};

  // 分页数据模型
  public pageInfo: PaginationModel = {
    currentPageNum: 1,
    pageSize: 10,
    totalPages: 1,
    total: 0,
    pagesShow: 5,
    startRow: 0,
    endRow: 0,
    pageList: [5, 10, 25, 50, 100]
  };

  // 与银行间模块数据交互的调度对象
  public exchangeDataReducer: Observable<any>;

  // 划款指令数据列表组件
  @ViewChild(ListComponent)
  public ListComponent: ListComponent;

  constructor(public store: Store<InterbankToTransferExchangeDataModel>,
    public router: ActivatedRoute,
    public service: TransferInstructionManageService) {
    this.isExchangeDataWithInterbankModule();
  }

  ngOnInit() {
    this.search();
  }

  ngAfterViewInit(): void {
    //  调用时间插件
    Util.daterangepickerPluginInit(".daterangepicker-plugin");
    Util.datepickerPluginInit(".daterangepicker-single");
  }

  /**
   * 发送请求通用函数
   * @param url 请求地址
   * @param method 请求方式
   * @param $event 点击的dom元素
   * @param status 所属状态名
   */
  public commonRequest(url, method, $event, status) {
    const that = this;
    const datas = this.takeIdFormDatas(this.ListComponent.getSelectedDatas());  // 在选中行数组中取出需要传递的ID包装数组，如果未选中长度为0
    if (that.isValidate(datas, status, $event)) {
      window["swal"]({
        title: "提示",
        text: `是否对此条数据进行${$event.target.textContent}操作?`,
        type: "info",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        closeOnConfirm: false,
        closeOnCancel: true,
        showLoaderOnConfirm: true
      }, function (isConfirm) {
        if (isConfirm) { // 确认
          that.service.sendCommonRequest(datas, url, method).subscribe(result => {
            // 如果接口返回结果出错
            if (result.code + '' !== '0') {
              window['swal']("提示", result.detailMsg, "error");
              return null;
            }
            that.switchStatus(that.nowStatus);
            window['swal']({
              title: "提示",
              text: `<div>${$event.target.textContent}成功</div>`,
              html: true,
              type: `success`
            });
            that.ListComponent.selectedDatas = [];
          });
        } else { // 取消
          // window["swal"]("Cancelled", "Your imaginary file is safe :)", "error");
        }
      });
    }
  }

  /**
   * 校验是否符合请求资格
   * @param datas 需要校验的数据
   * @param status 点击时请求所属的划款指令类型
   * @param $event  点击时的DOM元素
   */
  public isValidate(datas, status, $event) {
    let answer = false;
    const that = this;
    if (datas.hkInstructionId.length === 0) {
      window['swal']({
        title: "提示",
        text: `<div>请选择一条数据进行操作</div>`,
        html: true,
        type: "warning"
      });
      return answer;
    } else if (status === 'zlbh'){
      answer  = true;
    } else if (status !== 'zlbh') { // 指令驳回在任意一个流程都能点击,这里只对指令驳回之外的操作验证
      for (let i = 0; i < datas.hkInstructionStatus.length; i++) {
        if (status === 'shhkzl'){
          if(datas.hkInstructionRecheckUser[i] === sessionStorage.getItem('username')){
            window['swal']("提示", "到账确认复核与通过到账确认复核不能是同一个用户操作！", "error");
            return answer;
          }
        }
        if (!this.allStatus[status].includes(datas.hkInstructionStatus[i])) {
          window['swal']({
            title: "提示",
            text: status === 'zlcx' ? `<div>已撤销的状态下不能再次撤销</div>` : `<div>只有${that.status[this.allStatus[status]]}的数据才能进行${$event.target.textContent}操作</div>`,
            html: true,
            type: "warning"
          });
          return answer;
        } else {
          answer = true;
        }
      }
    }
    return answer;
  }

  /**
   * 剥离datas取出ID并包装查询数据对象
   * @param {any} datas 传进来的当前行数据
   * @returns
   * @memberof TransferInstructionComponent
   */
  public takeIdFormDatas(datas) {
    const search = {
      hkInstructionId: [],
      hkInstructionStatus: [],
      hkInstructionRecheckUser:[]
    };
    datas.forEach((item) => {
      search.hkInstructionId.push({ hkInstructionId: item.hkInstructionId });
      search.hkInstructionStatus.push(item.hkInstructionStatus);
      search.hkInstructionRecheckUser.push(item.instructionRecheckUser);
    });
    return search;
  }

  /**
   * 与银行间的数据交换，根据相关数据进行搜索展示
   */
  public isExchangeDataWithInterbankModule() {
    this.router.params.subscribe((params) => {
      if (params && params.flag && params.flag === 'true') {
        this.exchangeDataReducer = this.store.select('interbankToTransferModuleReducer');
      }
    });
    if (this.exchangeDataReducer != null) {
      this.exchangeDataReducer.subscribe((data) => {
        if (data && data.transferInstructionIds) {
          const searchObj: TFISeacrhModel = {
            hkInstructionId: data.transferInstructionIds.join(',')
          };
          this.getListData(searchObj);
        }
      });
    }
  }

  /**
   * 获取划款指令列表数据并渲染
   * @returns {Subscription}
   */
  public search(): Subscription {
    return this.getListData(this.wrapperSearchModule());
  }

  /**
   * 将所有搜索条件框重置为空
   */
  public resetSearch() {
    window["$"](".tfi-search-input").each(function () {
      this.value = "";
    });
  }

  /**
   * 获取划款指令列表数据,用包装好的search条件调用service中的getListData请求。
   * @param {search}
   */
  public getListData(search: TFISeacrhModel,
    currentPageNum: number = this.pageInfo.currentPageNum,
    pageSize: number = this.pageInfo.pageSize) {
    return this.service.getListData(search, currentPageNum, pageSize).subscribe((result) => {
      if (result != null && result.data != null && result.data.list != null) {
        this.data = [];
        this.data.list = result.data.list;
        this.pageInfo.totalPages = result.data.pages;
        this.pageInfo.total = result.data.total;
        this.pageInfo.startRow = result.data.startRow;
        this.pageInfo.endRow = result.data.endRow;
      }
    });
  }

  /**
   * 将用户输入的搜索条件包装成为一个搜索数据模型对象
   * @returns {TFISearchModel}
   */
  public wrapperSearchModule(): TFISeacrhModel {
    const $ = window["$"];
    const data: TFISeacrhModel = {};
    data.hkInstructionStatus = this.nowStatus;
    $(".tfi-search-input").each((index, item) => {
      const $item = Util.$(item);
      const type = item.type;
      const id = item.id;
      const value = item.value;
      const daterangepicker = $item.data('daterangepicker');
      if (id && id !== "") {
        if (id === "Date") {
          data[`start${id}`] = (value != null && value.length > 0) ? daterangepicker.startDate.format('YYYYMMDD') : "";
          data[`end${id}`] = (value != null && value.length > 0) ? daterangepicker.endDate.format('YYYYMMDD') : "";
        } else if (id === "instructionSendoutescrowDate") {
          data[`${id}s`] = (value != null && value.length > 0) ? daterangepicker.startDate.format('YYYYMMDD') : "";
          data[`${id}e`] = (value != null && value.length > 0) ? daterangepicker.endDate.format('YYYYMMDD') : "";
        } else {
          if (type === 'text' || type === 'select' || type === 'select-one') {
            data[id] = value;
          } else if (type === 'checkbox') {
            data[id] = item.checked ? value : "";
          }
        }
      }
    });
    return data;
  }

  /**
   * 切换划款类型Tab函数
   * @param {string} status 当前界面划款指令状态，默认是全部为空
   * @returns
   * @memberof TransferInstructionComponent
   */
  public switchStatus(status: any = "") {
    this.nowStatus = status;
    this.search();
    this.ListComponent.selectedDatas = [];
  };


  /**
   * 点击列表行时发生，接收List.component数据并保存到this.acceptData中
   * @param {*} data 列表被点击的行数据
   * @memberof TransferInstructionComponent
   */
  public acceptListData(data: any) {
    this.acceptData = data.item;
  }

  /**
   * 当模态框组件点击保存时发生，接受从Modal保存回来的数据
   * @param {*} returnData 从模态框返回修改的单行数据
   * @memberof TransferInstructionComponent
   */
  public acceptModalData(returnData: any) {
    // const that = this;
    // for (let i = 0; i < that.data.list.length; i++) {
    //   if (that.data.list[i].fundCode === returnData.item.fundCode) {
    //     that.data.list[i] = returnData.item;
    //   }
    // }
    this.search();
  }

  /**
   * 根据页码请求查询相关配置列表数据,如果当前活动页码就是目标页码，则不进行任何查询
   * 直接返回
   * @param {currentPageNum}
   */
  public pageNavigation(currentPageNum: number) {
    this.pageInfo.currentPageNum = currentPageNum;
    this.getListData(
      this.wrapperSearchModule(),
      this.pageInfo.currentPageNum,
      this.pageInfo.pageSize);
  }

  /**
   * 改变每页显示记录数
   * @param {pageSize}
   */
  public pageSizeChange(pageSize: number) {
    if (pageSize !== this.pageInfo.pageSize) {
      this.pageInfo.pageSize = pageSize;
      this.pageInfo.currentPageNum = 1;
      this.getListData(this.wrapperSearchModule(), 1, this.pageInfo.pageSize);
    }
  }
}
